/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import play.*;
import play.mvc.*;

import java.util.*;

import models.*;
import models.monorent.*;

import play.server.hybi10.Base64;
/**
 *
 * @author xuyuhang1005
 */
public class RestAuth {
    static public long auth(Http.Request req) {
        Http.Header authHeader = req.headers.get("authorization");
		if(authHeader == null) {
			return 0;
		}
		String authString = authHeader.value();
		authString = authString.split(" ")[1];
        try {
            authString = new String(Base64.decode(authString), "UTF8");
        } catch (UnsupportedEncodingException ex) {
            System.out.println("auth exception!");
        }
		String[] authInfo = authString.split(":");
		if(authInfo.length < 2) {
			return 0;
		}
		String authUsername = authInfo[0];
        authUsername = authUsername.trim().replace(";", "").replace(" ", "");
		String authPassword = authInfo[1];
        
        User user = User.connect(authUsername, authPassword);
        if(user == null) {
            return 0;
        } else {
            return user.id;
        }
    }
}
